package com.wecan.components.oss.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PolicyConditions;
import com.wecan.base.exception.app.FileUploadException;
import com.wecan.components.oss.properties.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.Date;

/**
 * @Author liuzhihao
 * @Date 2022.01.15
 * @Version 1.0.0
 * @Description oss文件服务层
 */
public class OSSService {

    @Autowired
    OSSProperties ossProperties;

    /**
     * 获取上传的oss客户端
     * @return
     */
    private OSS generateOssClient() {
        String endpoint = ossProperties.getEndpoint();
        String accessKey = ossProperties.getAccessKeyId();
        String accessSecret = ossProperties.getAccessKeySecret();
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, accessSecret);
        return ossClient;
    }

    /**
     * 获取次账号的oss客户端
     *
     * @return
     */
    private OSS generateThirdOssClient() {
        String endpoint = ossProperties.getEndpoint();
        String accessKey = ossProperties.getThirdAccessKeyId();
        String accessKeySecret = ossProperties.getThirdAccessKeySecret();
        return new OSSClientBuilder().build(endpoint, accessKey, accessKeySecret);
    }

    /**
     * 上传文件
     * @return
     */
    public boolean uploadFile(String objectName, ObjectMetadata objectMetadata, MultipartFile multipartFile) {
        OSS oss = generateOssClient();
        String bucketName = ossProperties.getBucketName();
        try {
            oss.putObject(bucketName, objectName, new ByteArrayInputStream(multipartFile.getBytes()), objectMetadata);
        } catch (Exception e) {
            throw new FileUploadException("文件上传失败");
        } finally {
            oss.shutdown();
        }
        return true;
    }

    /**
     * 删除文件
     * @return
     */
    public boolean deleteFile() {
        return true;
    }

    /**
     * 获取文件浏览地址
     * @return
     */
    public String getFileBrowUrl() {
        return null;
    }

    /**
     * 获取文件下载地址
     * @return
     */
    public String getFileDownUrl() {
        return null;
    }

    /**
     * 获取私域上传地址
     * @param path
     * @return
     */
    public JSONObject getPolicy(String path) {
        OSS oss = generateThirdOssClient();
        String endpoint = ossProperties.getEndpoint();
        String accessKey = ossProperties.getThirdAccessKeyId();
        String bucket = ossProperties.getBucketName();
        String host = "https://" + bucket + "." + endpoint;
        String callbackUrl = ossProperties.getCallbackUrl();
        try {
            long expireTime = 60000;
            long expireEndTime = System.currentTimeMillis() + expireTime;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConditions = new PolicyConditions();
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, path);
            String postPolicy = oss.generatePostPolicy(expiration, policyConditions);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = oss.calculatePostSignature(postPolicy);
            JSONObject respMap = new JSONObject();
            respMap.put("accessid", accessKey);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", path);
            respMap.put("host", host);
            respMap.put("expire", expireEndTime);
            JSONObject jasonCallback = new JSONObject();

            jasonCallback.put("callbackUrl", callbackUrl);
            jasonCallback.put("callbackBody", "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
            respMap.put("callback", base64CallbackBody);
            return respMap;
        } catch (Exception e) {
            return null;
        }
    }
}
